<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-11
 * Time: 17:44
 */

namespace app\service;


use app\common\model\MallConfig;
use EasyWeChat\Factory;
use think\Db;
use think\Exception;
use app\common\model\Grade as GradeModel;
use app\common\model\User as UserModel;
use app\common\model\Order as OrderModel;
use app\common\model\Mall as MallModel;
use app\common\model\Config as ConfigModel;
use app\common\model\Goods as GoodsModel;

class ThirdService extends BaseService
{
    public $openPlatform;
    public $officialAccount;
    public static $qunzhu_one_bili=0.1;//一级代理商比例
    public static $qunzhu_two_bili=0.05;//一级代理商比例

    public static $company_one_bili=0.1; //一级公司比例
    public static $company_two_bili=0.05; //二级公司比例

    public static $mtype_money=1;//打款类型 充值余额
    public static $mtype_yongjin=2;//打款类型 佣金
    public static $mtype_score=3;//打款类型 积分

    public function __construct($option)
    {
        if(!config('open_appid')) {
            config(ConfigModel::getConfig());
        }
        /**
         * {"app_id":"wxf00edc4a37870e34","secret":"267d21529683eee85687d77cb57e2736","token":"h3ExPWzA8x0HL5uC","aes_key":"uoJ1QJVpgcaeTxzRKDVNkJemTPrNjQSruRBkUnkkjtD"}
         */
       /*  $config = [
            'app_id'   => config('open_appid'),
            'secret'   => config('open_secret'),
            'token'    => config('open_token'),
            'aes_key'  => config('open_aeskey'),
        ];
        $this->openPlatform=Factory::openPlatform($config);

        if($option['mall_id']) {
            $mall = MallModel::getOne(['id'=>$option['mall_id']]);

            $this->officialAccount = $this->openPlatform->officialAccount($mall['authorizer_appid'], $mall['authorizer_refresh_token']);
        }else{
            if(config('authorizer_appid')) {
                $this->officialAccount = $this->openPlatform->officialAccount(config('authorizer_appid'), config('authorizer_refresh_token'));
            }
        } */
        $config = [
            'app_id' => config('wechat_appid'),
            'secret' => config('wechat_appsecret'),
            'response_type' => 'array',
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/api/login/wechat_callback',
            ]
        ];
        $this->officialAccount = Factory::officialAccount($config);
    }

    public static $grade_qunzhu=2;
    public static $grade_company=3;


    /* 拼三免一结束结算 */
    public function pinEnd ($order_id) {
        return false;
        $orderInfo = OrderModel::getOne(array('id'=>$order_id));
        if($orderInfo['fenyong_type']==1) {
            return false;
        }
        $userInfo = UserModel::getOne([
            'id' => $orderInfo['uid']
        ]);
        $orderList = OrderModel::getAll("main_order_id={$order_id} or id={$order_id}",'pin_money asc');
        //最小金额的订单金额返给用户
        $minMoney = $orderList[0]['pin_money'];
        UserModel::changeMoney($userInfo['id'],1,$minMoney,'拼团成功资金返还',$orderInfo);
    }

    /**
     * 回调分佣金
     * @param $order_id
     * @return bool|int|true
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function processing($order_id){
        $orderInfo = OrderService::S()->findOrder(array('id'=>$order_id));
       // dump($orderInfo);die;
        $userInfo = UserModel::getOne([
            'id' => $orderInfo['uid']
        ]);
        $mall = MallModel::getOneById($orderInfo['mall_id']);

        if($orderInfo['checked']!=1){
            LogService::S()->writeLog('processing','订单状态不正确:'.$order_id);
            return false;
        }
        if($orderInfo['is_use']==1){//订单已结算
            LogService::S()->writeLog('processing','订单已计算:'.$order_id);
            //return false;
        }


        /* 购买等级 */
        if($orderInfo['shop_type']==4) {
            return false;
            $one_bili=0.2;
            $two_bili=0.1;
            $three_bili=0.1;
            $forth_bili=0.05;

            $goodsList = json_decode($orderInfo['goods_list'],true);
            $goods = $goodsList[0];
            $grade = $goods['grade'];
            GradeModel::changeGrade($userInfo['id'],$userInfo['grade_id'],$grade);
            //分佣金
            $refer = UserModel::getOne([
                'id' => $userInfo['refer_id']
            ]);
            /*if($grade!=2 || $grade!=4) {//只处理代理商 和店长 分公司线下处理
                return false;
            }*/
            if(!$refer) {
                return false;
            }
            //dump($userInfo['refer_id']);die;
            $one_dianzhang=UserModel::getFirstRefer($userInfo['refer_id'],4,true);//店长
           // dump($one_dianzhang);die;
            if($one_dianzhang){
                $two_uid=$one_dianzhang['refer_id'];
            }else{
                $two_uid=$userInfo['refer_id'];
            }

            $two_dailizhang=UserModel::getFirstRefer($two_uid,2,true);//代理商
            if($two_dailizhang){
                $three_uid=$two_dailizhang['refer_id'];
            }else{
                $three_uid=$two_uid;
            }
            //dump($three_uid);die;
            $three_dailizhang=UserModel::getFirstRefer($three_uid,3,true);//分公司
            //dump($three_dailizhang);die;
            //dump($three_dailizhang);die;
            if($three_dailizhang){
                $forth_uid=$three_dailizhang['id'];
            }else{
                $forth_uid=$three_uid;
            }

            $forth_dailizhang=UserModel::getFirstRefer($forth_uid,3,false);//上级分公司
           // dump($forth_dailizhang);die;
           // dump($forth_dailizhang);die;
            //dump($one_dianzhang);die;
            if($one_dianzhang){
                //本人返倍积分
                $money = round($orderInfo['pin_money']*$one_bili,2);
                $log[]=UserModel::changeMoney($one_dianzhang['id'],1,$money,"店长佣金",$orderInfo);
            }else{
                $two_bili+=$one_bili; //二级比例给上级
            }

            if($two_dailizhang){
                //代理商返回佣金
                $money = round($orderInfo['pin_money']*$two_bili,2);
                $log[]=UserModel::changeMoney($two_dailizhang['id'],1,$money,"代理商佣金",$orderInfo);
            }else{
                $three_bili+=$two_bili;
            }
            //dump($orderInfo['pin_money']*$three_bili);die;
            if($three_dailizhang){
                //分公司返回佣金
                $money = round($orderInfo['pin_money']*$three_bili,2);
                $log[]=UserModel::changeMoney($three_dailizhang['id'],1,$money,"分公司佣金",$orderInfo);
            }else{
                $forth_bili+=$two_bili;
            }

            if($forth_dailizhang){
                //分公司返回佣金
                $money = round($orderInfo['pin_money']*$forth_bili,2);
                $log[]=UserModel::changeMoney($forth_dailizhang['id'],1,$money,"平级分公司佣金",$orderInfo);
            }
            OrderService::S()->saveOrder(array('is_use'=>1),array('id'=>$order_id));
            return;
        }

        /* 购买商品 */
        if($orderInfo['shop_type']==1) {

            //分佣金
            $refer = UserModel::getOne([
                'id' => $userInfo['refer_id']
            ]);
            $grade=$userInfo['grade_id'];

            if(!$refer) {
                return false;
            }

            $score = round($orderInfo['pin_money']*config('score_bili'),2);
            UserModel::changeMoney($orderInfo['uid'],2,$score,'购物返积分',$orderInfo);
            $qunzhu1_bili = config('yongjin_grade2_floor1');
            $dianzhang1=$qunzhu1 = $qunzhu2 = $zongdai1 = $zongdai2 = false;
            $qunzhu1 = UserModel::getFirstRefer($userInfo['id'],2);
            if($qunzhu1) {
                $money = round($orderInfo['pin_money']*$qunzhu1_bili,2);
                UserModel::changeMoney($qunzhu1['id'],1,$money,'代理商奖励',$orderInfo);
            } 
            return;
        }

        //下单成功通知管理员
        $manager = MallConfig::getValue(['name' => 'order_manager', 'mall_id' => $userInfo['mall_id']], 'value');
        $order_manager = explode(',', $manager ? $manager : config('order_manager'));
        if ($order_manager) {
            $manager_info = \app\common\model\User::getAll(['id' => ['in', $order_manager]]);
            if ($manager_info) {
                $shop_type = [
//                    1 => '主商城',
                    2 => '积分商城',
//                    4 => '升级商品',
//                    6 => '主播商品'
                ];

                foreach ($manager_info as $value) {
                    MsgService::S(['mall_id' => $value['mall_id']])->sendTemp('NEW_ORDER', $value['mall_id'], $value['id'], [
                        'first' => '系统有新的订单',
                        'order_sn' => $orderInfo['order_sn'],
                        'type' => isset($shop_type[$orderInfo['shop_type']]) ? $shop_type[$orderInfo['shop_type']] : '',
                        'all_money' => $orderInfo['all_money'],
                        'time' => $orderInfo['create_time'],
                        'userinfo' => $userInfo['nickname'] . '(ID:' . $userInfo['id'] . ')',
                        'remark' => "系统有新的订单信息，可前往管理后台查看"
                    ]);
                }
            }
        }

        /* 购买积分商品 */
        if($orderInfo['shop_type']==2) {
            return;
        }

        return true;
    }



}